<template>
  <div class="infoBox">
    <el-drawer
      :visible.sync="dialogVisible"
      :title="isAtud ? $t('shangPinShenHe') : $t('shangPinXiangQing')"
      :direction="direction"
      :append-to-body="true"
      custom-class="demo-drawer"
      size="1000px"
      :wrapperClosable="isAtud ? false : true"
      :modal-append-to-body="false"
      class="infoBox"
    >
      <div class="demo-drawer__content">
        <div class="divBox">
          <div slot="header" class="clearfix">
            <el-tabs v-model="currentTab">
              <el-tab-pane :label="$t('shangPinXinXi')" name="0" />
              <!-- <el-tab-pane :label="$t('shangPinXiangQing')" name="1" /> -->
            </el-tabs>
          </div>
          <el-descriptions v-show="currentTab === '0'" :column="2" border>
            <el-descriptions-item
              v-for="(item, index) in detailData"
              :key="index"
              :label="item.label"
              :span="item.span || 1"
            >
              <el-image
                v-if="item.type === 'image'"
                style="width: 100px !important; height: 100px !important"
                :src="item.value"
                :preview-src-list="[item.value]"
                fit="contain"
              />
              <template v-else>{{ item.value }}</template>
            </el-descriptions-item>
          </el-descriptions>
          <div v-show="currentTab === '1'" v-html="storeInfo" />
        </div>
      </div>
      <div v-if="isAtud" class="from-foot-btn btn-shadow">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm">
          <el-form-item :label="$t('shenHeZhuangTai')" prop="auditStatus">
            <el-radio-group v-model="ruleForm.auditStatus">
              <el-radio label="success">{{ $t('tongGuo') }}</el-radio>
              <el-radio label="fail">{{ $t('juJue') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="ruleForm.auditStatus === 'fail'" :label="$t('yuanYin')" prop="reason">
            <el-input v-model="ruleForm.reason" type="textarea" />
          </el-form-item>
          <el-form-item v-if="ruleForm.auditStatus === 'success'&&isAuditBrand" :label="$t('pinPai')" prop="brandId">
            <el-select
              v-model="ruleForm.brandId"
              v-selectLoadMore="selectLoadMore"
              class="selWidth"
              clearable
              filterable
              remote
              :remote-method="remoteMethod"
              :placeholder="$t('qingXuanZePinPai')"
              default-first-option
              popper-class="custom-popper"
              maxlength="50"
              @change="brandChange"
            >
              <el-option v-for="user in brandList" :key="user.id" :label="user.name" :value="user.id" :disabled="user.disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="close">{{ $t('cancel') }}</el-button>
            <el-button type="primary" @click="onSubmit('ruleForm')">{{
              loadingBtn ? $t('tiJiaoZhong') + ' ...' : $t('confirm')
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import i18n from '../../../lang/index';
import Tinymce from '@/components/Tinymce/index';
import {
  productCouponListApi,
  productAuditApi,
  brandListApi,
  guaranteeListApi,
  productCreateApi,
  categoryApi,
  productDetailApi,
  productUpdateApi,
} from '@/api/store';
import { Debounce } from '@/utils/validate';
import { mapGetters } from 'vuex';
import { detectLanguage, isJSON } from '@/utils/index.js';

export default {
  directives: {
    // 计算是否滚动到最下面
    selectLoadMore: {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          if (this.scrollHeight - this.scrollTop < this.clientHeight + 1) {
            binding.value()
          }
        })
      }
    }
  },
  name: 'ProductProductAdd',
  props: {
    isShow: {
      type: Boolean,
      default: true,
    },
    isAtud: {
      type: Boolean,
      default: false,
    },
    productId: {
      type: [Number, String],
      default: () => null,
    },
  },
  components: { Tinymce },
  data() {
    return {
      rules: {
        auditStatus: [{ required: true, message: this.$t('qingXuanZeShenHeZhuangTai'), trigger: 'change' }],
        reason: [{ required: true, message: this.$t('qingTianXieJuJueYuanYin'), trigger: 'blur' }],
        brandId: [{ required: true, message: this.$t('qingXuanZePinPai'), trigger: 'change' }],
      },
      ruleForm: {
        reason: '',
        auditStatus: 'success',
        idList: '',
        brandId:''
      },
      direction: 'rtl',
      dialogVisible: false,
      isDisabled: true,
      fullscreenLoading: false,
      isBtn: false,
      currentTab: '0',
      tempRoute: {},
      loading: false,
      loadingBtn: false,
      detailData: [],
      storeInfo: '',
      brandList: [],
      search: {
        limit: 10,
        page: 1,
        name: '',
      },
      isAuditBrand:false
    };
  },
  computed: {
    ...mapGetters(['adminProductClassify', 'productBrand', 'translateAdminProductClassifyArr']),
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route);

    if (!this.adminProductClassify.length) this.$store.dispatch('product/getAdminProductClassify');
    // if(!this.productBrand.length)
    //   this.$store.dispatch('product/getMerProductBrand')
  },
  mounted() {
    if (!this.translateAdminProductClassifyArr.length) this.$store.dispatch('product/getAdminProductClassify');
    if (this.$route.params.id) {
      this.setTagsViewTitle();
      this.getInfo();
    }
  },
  methods: {
    close() {
      this.dialogVisible = false;
    },
    // 下拉加载更多
    selectLoadMore() {
      if (this.search.limit < 10) {
        this.search.limit = 10
      }
      this.search.limit = this.search.limit + 5
      if (this.search.limit > this.totalPage) return
      this.getbrandList() // 请求接口
    },
    // 远程搜索
    remoteMethod(query) {
      this.loading = true
      this.search.name = query
      this.search.limit = 10
      this.brandList = []
      setTimeout(() => {
        this.loading = false
        this.getbrandList() // 请求接口
      }, 200)
    },
    // 品牌列表
    getbrandList() {
      brandListApi(this.search).then((res) => {
        this.brandList = res.list;
        this.totalPage = res.total
      });
    },
    brandChange() {
      if (!this.ruleForm.brandId) {
        this.search.name = ''
        this.getbrandList()
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loadingBtn = true;
          this.ruleForm.idList = [this.productId];
          productAuditApi(this.ruleForm)
            .then((res) => {
              this.$message.success(this.$t('caoZuoChengGong'));
              this.ruleForm= {
                reason: '',
                auditStatus: 'success',
                idList: '',
                brandId:''
              }
              this.dialogVisible = false;
              this.currentTab = '0';
              this.$emit('subSuccess');
              this.loadingBtn = false;

            })
            .catch((res) => {
              this.loadingBtn = false;
            });
        } else {
          return false;
        }
      });
    },
    setTagsViewTitle() {
      const title = this.isDisabled ? this.$t('shangPinXiangQing') : this.$t('bianJiShangPin');
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.$route.params.id}` });
      this.$store.dispatch('tagsView/updateVisitedView', route);
    },
    // 详情
    getInfo(id) {
      this.loading = true;
      productDetailApi(id).then((res) => {
        this.detailData = [
          { label: this.$t('shangPinId'), value: res.skuCode },
          { label: this.$t('shangPinMingCheng'), value: res.storeName },
          { label: this.$t('shangPinWeiYiMa'), value: res.skuOnlyCode },
          { label: this.$t('shangPinGuiGe'), value: res.specType ? this.$t('duoGuiGe') : this.$t('danGuiGe') },
          { label: this.$t('shangPinFenLei'), value: this.getCategoryName(res.categoryId) },
          { label: this.$t('pinPai'), value: res.brandName },
          { label: this.$t('zheKouJia'), value: res.price },
          { label: this.$t('yuanJia'), value: res.originalPrice },
          { label: '商品Halyk售价', value: res.salePrice },
          { label: 'HSCODE', value: res.hsCode },
          { label: this.$t('shiFouDaiDian'), value: res.electricityFlag === 'Y' ? this.$t('yes') : this.$t('no') },
          { label: this.$t('shangPinChiCun'), value: `${res.skuLength}*${res.skuWidth}*${res.skuHeight} CM` },
          { label: this.$t('zhongLiang'), value: `${res.skuWeight}KG` },
          { label: this.$t('yanSe'), value: res.skuColor },
          { label: this.$t('xingHao'), value: res.skuModel },
          { label: this.$t('kuCunShu'), value: res.stock, span: 2 },
          { label: this.$t('shangPinZhuTu'), value: res.image, type: 'image', span: 2 },
          { label: this.$t('shangPinZhanShiTu'), value: res.flatPattern, type: 'image', span: 2 },
          { label: this.$t('shangPinLunBoTu'), value: res.sliderImage, type: 'image', span: 2 },
          { label: this.$t('shangPinXiangQing'), value: res.storeInfo, span: 2 },
          { label: this.$t('juJueYuanYin'), value: res.reason, span: 2 }
        ];
        this.storeInfo = res.content;
        this.isAuditBrand = res.isAuditBrand
      });

      this.getbrandList();
    },
    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$message.warning(error);
      }
    },
    getCategoryName(categoryId) {
      const obj = this.translateAdminProductClassifyArr.find((e) => {
        return e.id == categoryId;
      });
      return obj ? obj.translateName : '';
    },
  },
};
</script>
<style scoped lang="scss">

::v-deep .el-descriptions {
  .el-descriptions-item__label.is-bordered-label {
    min-width: 100px;
  }
  .el-descriptions-item__cell {
    white-space: normal; /* 保留空白符序列，但是正常换行 */
    word-break: break-all;
  }
}
</style>
